package com.aliwo.controller;

import com.alibaba.druid.util.StringUtils;
import com.aliwo.response.ResultResponse;
import com.aliwo.utils.CommonUtil;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * .
 *
 * @author Xu Yayuan
 * @date 2023-04-03
 */
@RestController
public class CaptchaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Producer captchaProducer;

    // 图形验证码有效期10分钟
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    /**
     * 获取图形验证码
     *
     * @param request  request
     * @param response 图形验证码
     * @author xuyy
     */
    @RequestMapping(value = "captcha", method = RequestMethod.GET)
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = captchaProducer.createText();
        stringRedisTemplate.opsForValue().set(this.getCaptchaKey(request), captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 支持手机号、邮箱发送验证码
     *
     * @return ResultResponse
     */
    @GetMapping("send_code")
    public ResultResponse sendRegisterCode(@RequestParam(value = "to") String to,
                                           @RequestParam(value = "captcha") String captcha,
                                           HttpServletRequest request) {
        // 从缓存中获取图形验证码的key
        String key = getCaptchaKey(request);
        // 从缓存中获取图形验证码的value
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(key);
        if (!Objects.isNull(captcha) && !StringUtils.isEmpty(cacheCaptcha) && cacheCaptcha.equalsIgnoreCase(captcha)) {
            stringRedisTemplate.delete(key);
            // todo 发送短信验证码

            return ResultResponse.buildSuccess();
        } else {
            return ResultResponse.buildError("验证码错误");
        }
    }

    /**
     * 获取缓存的key
     *
     * @param request request
     * @return java.lang.String
     * @author xuyy
     */
    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        return "user-service:captcha:" + CommonUtil.MD5(ip + userAgent);
    }

}
